#include <stdio.h>
#include <utmp.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <dirent.h>
#include <grp.h>
#include <pwd.h>
#include <sys/types.h>
#include <stdbool.h>
#include <ctype.h>
#include <sys/resource.h>
#include <sys/utsname.h>
#include <sys/sysinfo.h>
#include <sys/types.h>
#include <assert.h>
#include "CUnit/Basic.h"
#include "CUnit/TestDB.h"
#include "CUnit/CUnit.h"

#define NUM_PROCS 100
#define MAX_SIZE 1024
#define PROC_LEN 128
#define THREAD_LEN 64
#define THREAD_NUM 10

typedef struct LinkedListNode {
    char str[1024];
    struct LinkedListNode *next;
} Node;

typedef struct UsageInformationLinkedLists {
    Node *mem_usage_list_head; 
    Node *mem_usage_list_tail; 
    Node *cpu_usage_list_head; 
    Node *cpu_usage_list_tail; 
    float last_mem_usage; 
    int lastTotal; 
    int lastIdle;
} UsageInfoLL;

typedef struct proc_info {
    struct proc_info *next;
    pid_t pid;
    pid_t tid;
    uid_t uid;
    gid_t gid;
    char name[PROC_LEN];
    char tname[THREAD_LEN];
    char state;
    long unsigned utime;
    long unsigned stime;
    long unsigned delta_utime;
    long unsigned delta_stime;
    long unsigned delta_time;
    long vss;
    long rss;
    int num_threads;
    char policy[32];
}proc_info;
 
struct proc_list {
    struct proc_info **array;
    int size;
};

struct cpu_info {
    long unsigned utime, ntime, stime, itime;
    long unsigned iowtime, irqtime, sirqtime;
};

static struct proc_info **old_procs, **new_procs;
static int num_old_procs, num_new_procs;
static struct proc_info *free_procs;
static int num_used_procs, num_free_procs;
static int max_procs, delay, iterations, threads;
static struct cpu_info old_cpu, new_cpu;
static int (*proc_cmp)(const void *a, const void *b);
bool parseArguments(int argc, char **argv, int *samples, int *tdelay, bool *systemFlagPresent, 
                    bool *userFlagPresent, bool *graphicsFlagPresent);
#define error_output(...) { fprintf(stderr, __VA_ARGS__); exit(EXIT_FAILURE); }

static int numcmp(long long a, long long b) {
    if (a < b) return -1;
    if (a > b) return 1;
    return 0;
}

static int proc_cpu_cmp(const void *a, const void *b) {
    struct proc_info *pa, *pb;
 
    pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
 
    if (!pa && !pb) return 0;
    if (!pa) return 1;
    if (!pb) return -1;
 
    return -numcmp(pa->delta_time, pb->delta_time);
}

static int read_stat(char *filename, struct proc_info *proc) {
    FILE *file;
    char buf[MAX_SIZE], *open_paren, *close_paren;
    int res, idx;
    file = fopen(filename, "r");
    if (!file) return 1;
    fgets(buf, MAX_SIZE, file);
    fclose(file);
    open_paren = strchr(buf, '(');
    close_paren = strrchr(buf, ')');
    if (!open_paren || !close_paren) return 1;
 
    *open_paren = *close_paren = '\0';
    strncpy(proc->tname, open_paren + 1, THREAD_LEN);
    proc->tname[THREAD_LEN-1] = 0;
    
    sscanf(close_paren + 1, " %c %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
                 "%lu %lu %*d %*d %*d %*d %*d %*d %*d %ld %ld",
                 &proc->state, &proc->utime, &proc->stime, &proc->vss, &proc->rss);
    return 0;
}

static int read_status(char *filename, struct proc_info *proc) {
    FILE *file;
    char line[MAX_SIZE];
    unsigned int uid, gid;
 
    file = fopen(filename, "r");
    if (!file) return 1;
    while (fgets(line, MAX_SIZE, file)) {
        sscanf(line, "Uid: %u", &uid);
        sscanf(line, "Gid: %u", &gid);
    }
    fclose(file);
    proc->uid = uid; proc->gid = gid;
    return 0;
}

static int read_cmdline(char *filename, struct proc_info *proc) {
    FILE *file;
    char line[MAX_SIZE];
 
    line[0] = '\0';
    file = fopen(filename, "r");
    if (!file) return 1;
    fgets(line, MAX_SIZE, file);
    fclose(file);
    if (strlen(line) > 0) {
        strncpy(proc->name, line, PROC_LEN);
        proc->name[PROC_LEN-1] = 0;
    } else
        proc->name[0] = 0;
    return 0;
}

static struct proc_info *alloc_proc(void) {
    struct proc_info *proc;
 
    if (free_procs) {
        proc = free_procs;
        free_procs = free_procs->next;
        num_free_procs--;
    } else {
        proc = malloc(sizeof(*proc));
        if (!proc) error_output("Could not allocate struct process_info.\n");
    }
 
    num_used_procs++;
 
    return proc;
}

static struct proc_info *find_old_proc(pid_t pid, pid_t tid) {
    int i;
 
    for (i = 0; i < num_old_procs; i++)
        if (old_procs[i] && (old_procs[i]->pid == pid) && (old_procs[i]->tid == tid))
            return old_procs[i];
 
    return NULL;
}

static void add_proc(int proc_num, struct proc_info *proc) {
    int i;
 
    if (proc_num >= num_new_procs) {
        new_procs = realloc(new_procs, 2 * num_new_procs * sizeof(struct proc_info *));
        if (!new_procs) error_output("Could not expand procs array.\n");
        for (i = num_new_procs; i < 2 * num_new_procs; i++)
            new_procs[i] = NULL;
        num_new_procs = 2 * num_new_procs;
    }
    new_procs[proc_num] = proc;
}

float calculateCPUUsage(int *lastTotal, int *lastIdle) {
    FILE *fp = fopen("/proc/stat", "r"); 
    char stat_str[1024]; 
    fgets(stat_str, 1024, fp); 
    fclose(fp);
    int total_time;
    float cpu_usage;

    char *token = strtok(stat_str, " ");
    token = strtok(NULL, " "); 
    int user = atoi(token);
    token = strtok(NULL, " ");
    int nice = atoi(token);
    token = strtok(NULL, " "); 
    int system = atoi(token);
    token = strtok(NULL, " "); 
    int idle = atoi(token);
    token = strtok(NULL, " ");
    int iowait = atoi(token);
    token = strtok(NULL, " ");
    int irq = atoi(token);
    token = strtok(NULL, " ");
    int softirq = atoi(token);
    token = strtok(NULL, " ");
    int steal = atoi(token);
    token = strtok(NULL, " ");
    int guest = atoi(token);
    total_time = user + nice + system + idle + iowait + irq + softirq + steal + guest;

    if (*lastTotal == -1 && *lastIdle == -1) {
        cpu_usage = 0;    
    } 
    else { 
        cpu_usage = 100 - (idle - *lastIdle) * 100.0 / (total_time - *lastTotal);;
    }

    *lastTotal = total_time;
    *lastIdle = idle;

    return cpu_usage;

}

void deleteList(Node *head) {
    Node *p = NULL;
    Node *q = NULL;
    p = head;
    while (p != NULL) {
        q = p->next;
        free(p);
        p = q;
    }
}


void generateMemoryUsage(int samples, int tdelay, UsageInfoLL *usageInfo, int i) {
    
    struct rusage r;
    struct sysinfo s;
    
    float total_ram; 
    float free_ram; 
    float total_swap; 
    float free_swap; 
    float swap_used;
    float phys_mem_used; 
    float virtual_mem_used; 
    float total_memory;
    
    getrusage(RUSAGE_SELF, &r); 
    printf("---------------------------------------\n");
    printf("内存占用 (物理 已使用/总计 -- 虚拟 已使用/总计)\n");
    Node *new_sample_mem = (Node *)calloc(1, sizeof(Node));
    new_sample_mem->next = NULL;
    if (usageInfo->mem_usage_list_head == NULL) {
        usageInfo->mem_usage_list_head = new_sample_mem;
        usageInfo->mem_usage_list_tail = new_sample_mem;
    }
    else {
        usageInfo->mem_usage_list_tail->next = new_sample_mem;
        usageInfo->mem_usage_list_tail = new_sample_mem;
    }
    strcpy(new_sample_mem->str, "");
    sysinfo(&s); 
    total_ram = (float)s.totalram/s.mem_unit/1000000000;
    free_ram = (float)s.freeram/s.mem_unit/1000000000;
    total_swap =(float)s.totalswap/s.mem_unit/1000000000;
    free_swap =(float)s.freeswap/s.mem_unit/1000000000;
    
    total_memory = total_ram + total_swap;
    phys_mem_used = total_ram - free_ram;
    swap_used = total_swap - free_swap;
    virtual_mem_used = phys_mem_used + swap_used;

    sprintf(new_sample_mem->str, "%.2f GB / %.2f GB -- %.2f GB / %.2f GB", phys_mem_used, total_ram, 
                virtual_mem_used, total_memory);
    
    Node *mp = usageInfo->mem_usage_list_head;
    while (mp != NULL) {
        printf("%s\n", mp->str); 
        mp = mp->next;
    }
}

void generateCPUUsage(int samples, int tdelay, UsageInfoLL *usageInfo, int i) {
    
    printf("---------------------------------------\n");
    printf("核心数: %ld\n", sysconf(_SC_NPROCESSORS_ONLN)); 

}


void generateMemoryUsageGraphics(int samples, int tdelay, UsageInfoLL *usageInfo, int i) {
    
    struct rusage r;

    struct sysinfo s;
    
    float total_ram; 
    float free_ram; 
    float total_swap;
    float free_swap; 
    float swap_used;
    float phys_mem_used; 
    float virtual_mem_used; 
    float total_memory; 

    float delta_mem_use; 
    float rounded_delta_mem_use; 

    getrusage(RUSAGE_SELF, &r); 
    //printf(" Memory usage: %ld kilobytes\n", r.ru_maxrss);
    printf("---------------------------------------\n");
    printf("内存占用 (物理 已使用/总计 -- 虚拟 已使用/总计)\n");
    Node *new_sample_mem = (Node *)calloc(1, sizeof(Node)); 
    
    new_sample_mem->next = NULL;
    if (usageInfo->mem_usage_list_head == NULL) {
        usageInfo->mem_usage_list_head = new_sample_mem;
        usageInfo->mem_usage_list_tail = new_sample_mem;
    }
    else {
        usageInfo->mem_usage_list_tail->next = new_sample_mem;
        usageInfo->mem_usage_list_tail = new_sample_mem;
    }
    strcpy(new_sample_mem->str, "");
    sysinfo(&s); 
    total_ram = (float)s.totalram/s.mem_unit/1000000000;
    free_ram = (float)s.freeram/s.mem_unit/1000000000;
    total_swap =(float)s.totalswap/s.mem_unit/1000000000;
    free_swap =(float)s.freeswap/s.mem_unit/1000000000;
    
    total_memory = total_ram + total_swap;
    phys_mem_used = total_ram - free_ram;
    swap_used = total_swap - free_swap;
    virtual_mem_used = phys_mem_used + swap_used;

    sprintf(new_sample_mem->str, "%.2f GB / %.2f GB -- %.2f GB / %.2f GB\t|", phys_mem_used, total_ram, 
                virtual_mem_used, total_memory);

    if (usageInfo->last_mem_usage == -1) { 
        delta_mem_use = 0; 
        strcat(new_sample_mem->str, "o");
    }
    else { 
        delta_mem_use = (virtual_mem_used - usageInfo->last_mem_usage) / (usageInfo->last_mem_usage);
        char temp_rounded[6];
        sprintf(temp_rounded, "%.2f", delta_mem_use);
        rounded_delta_mem_use = atof(temp_rounded);

        if (rounded_delta_mem_use == 0.00 && delta_mem_use > 0) {
            strcat(new_sample_mem->str, "o");
        }
        else if (rounded_delta_mem_use == 0.00 && delta_mem_use < 0) {
            strcat(new_sample_mem->str, "@");
        }
        else if (rounded_delta_mem_use > 0) {
            for (float i = 0; i < delta_mem_use; i += 0.01) {
                strcat(new_sample_mem->str, "#");
            }
            strcat(new_sample_mem->str, "*");
        }
        else if (rounded_delta_mem_use < 0) {
            for (float i = 0; i < -delta_mem_use; i += 0.01) {
                strcat(new_sample_mem->str, ":");
            }
            strcat(new_sample_mem->str, "@");
        }
        
    }
    char temp_str[100];
    sprintf(temp_str, " %.2f (%.2f)", delta_mem_use, virtual_mem_used);
    strcat(new_sample_mem->str, temp_str);
    
    usageInfo->last_mem_usage = virtual_mem_used; 
    Node *mp = usageInfo->mem_usage_list_head;
    while (mp != NULL) {
        printf("%s\n", mp->str); 
        mp = mp->next;
    }
    
    for (int j = 0; j < samples - i - 1; j++)
        printf("\n");
}


void generateCPUUsageGraphics(int samples, int tdelay, UsageInfoLL *usageInfo, int i) {

    printf("---------------------------------------\n");
    printf("核心数: %ld\n", sysconf(_SC_NPROCESSORS_ONLN)); 
    float cpu_usage = calculateCPUUsage(&(usageInfo->lastTotal), &(usageInfo->lastIdle));
    printf(" cpu总占用 = %.2f%%\n", cpu_usage); 

    Node *new_sample = (Node *)calloc(1, sizeof(Node)); 
    new_sample->next = NULL;
    if (usageInfo->cpu_usage_list_head == NULL) {
        usageInfo->cpu_usage_list_head = new_sample;
        usageInfo->cpu_usage_list_tail = new_sample;
    }
    else {
        usageInfo->cpu_usage_list_tail->next = new_sample;
        usageInfo->cpu_usage_list_tail = new_sample;
    }
    strcpy(new_sample->str, "");
    if (cpu_usage < 1)
        strcat(new_sample->str, "*");
    else {
        for (int b = 0; b < cpu_usage; b++) {
            strcat(new_sample->str, "|");
        }
    }
    
    char cpu_usage_str[100];
    sprintf(cpu_usage_str, " %.2f%%", cpu_usage);
    strcat(new_sample->str, cpu_usage_str);

    Node *p = usageInfo->cpu_usage_list_head;
    while (p != NULL) {
        printf("\t%s\n", p->str); 
        p = p->next;
    }
    
    for (int j = 0; j < samples - i - 1; j++)
        printf("\n");
        
}
 
static void free_proc(struct proc_info *proc) {
    proc->next = free_procs;
    free_procs = proc;
 
    num_used_procs--;
    num_free_procs++;
}
 
static void read_procs(void) {
    DIR *proc_dir, *task_dir;
    struct dirent *pid_dir, *tid_dir;
    char filename[64];
    FILE *file;
    int proc_num;
    struct proc_info *proc;
    pid_t pid, tid;
 
    int i;
 
    proc_dir = opendir("/proc");
    if (!proc_dir) error_output("Could not open /proc.\n");
 
    new_procs = calloc(NUM_PROCS * (threads ? THREAD_NUM : 1), sizeof(struct proc_info *));
    num_new_procs = NUM_PROCS * (threads ? THREAD_NUM : 1);
 
    file = fopen("/proc/stat", "r");
    if (!file) error_output("Could not open /proc/stat.\n");
    fscanf(file, "cpu  %lu %lu %lu %lu %lu %lu %lu", &new_cpu.utime, &new_cpu.ntime, &new_cpu.stime,
            &new_cpu.itime, &new_cpu.iowtime, &new_cpu.irqtime, &new_cpu.sirqtime);
    fclose(file);
 
    proc_num = 0;
    while ((pid_dir = readdir(proc_dir))) {
        if (!isdigit(pid_dir->d_name[0]))
            continue;
 
        pid = atoi(pid_dir->d_name);
        
        struct proc_info cur_proc;
        
        if (!threads) {
            proc = alloc_proc();
 
            proc->pid = proc->tid = pid;
 
            sprintf(filename, "/proc/%d/stat", pid);
            read_stat(filename, proc);
 
            sprintf(filename, "/proc/%d/cmdline", pid);
            read_cmdline(filename, proc);
 
            sprintf(filename, "/proc/%d/status", pid);
            read_status(filename, proc);
 
            //read_policy(pid, proc);
 
            proc->num_threads = 0;
        } else {
            sprintf(filename, "/proc/%d/cmdline", pid);
            read_cmdline(filename, &cur_proc);
 
            sprintf(filename, "/proc/%d/status", pid);
            read_status(filename, &cur_proc);
            
            proc = NULL;
        }
 
        sprintf(filename, "/proc/%d/task", pid);
        task_dir = opendir(filename);
        if (!task_dir) continue;
 
        while ((tid_dir = readdir(task_dir))) {
            if (!isdigit(tid_dir->d_name[0]))
                continue;
 
            if (threads) {
                tid = atoi(tid_dir->d_name);
 
                proc = alloc_proc();
 
                proc->pid = pid; proc->tid = tid;
 
                sprintf(filename, "/proc/%d/task/%d/stat", pid, tid);
                read_stat(filename, proc);
 
                //read_policy(tid, proc);
 
                strcpy(proc->name, cur_proc.name);
                proc->uid = cur_proc.uid;
                proc->gid = cur_proc.gid;
 
                add_proc(proc_num++, proc);
            } else {
                proc->num_threads++;
            }
        }
 
        closedir(task_dir);
        
        if (!threads)
            add_proc(proc_num++, proc);
    }
 
    for (i = proc_num; i < num_new_procs; i++)
        new_procs[i] = NULL;
 
    closedir(proc_dir);
}
 
static void print_procs(void) {
    int i;
    struct proc_info *old_proc, *proc;
    long unsigned total_delta_time;
    struct passwd *user;
    struct group *group;
    char *user_str, user_buf[20];
    char *group_str, group_buf[20];
 
    for (i = 0; i < num_new_procs; i++) {
        if (new_procs[i]) {
            old_proc = find_old_proc(new_procs[i]->pid, new_procs[i]->tid);
            if (old_proc) {
                new_procs[i]->delta_utime = new_procs[i]->utime - old_proc->utime;
                new_procs[i]->delta_stime = new_procs[i]->stime - old_proc->stime;
            } else {
                new_procs[i]->delta_utime = 0;
                new_procs[i]->delta_stime = 0;
            }
            new_procs[i]->delta_time = new_procs[i]->delta_utime + new_procs[i]->delta_stime;
        }
    }
 
    total_delta_time = (new_cpu.utime + new_cpu.ntime + new_cpu.stime + new_cpu.itime
                        + new_cpu.iowtime + new_cpu.irqtime + new_cpu.sirqtime)
                     - (old_cpu.utime + old_cpu.ntime + old_cpu.stime + old_cpu.itime
                        + old_cpu.iowtime + old_cpu.irqtime + old_cpu.sirqtime);
 
    qsort(new_procs, num_new_procs, sizeof(struct proc_info *), proc_cmp);
    printf("进程运行时间分类统计\n");
    printf("用户进程 %ld%%, 系统进程 %ld%%, IO %ld%%, 硬中断 %ld%%\n",
            ((new_cpu.utime + new_cpu.ntime) - (old_cpu.utime + old_cpu.ntime)) * 100  / total_delta_time,
            ((new_cpu.stime ) - (old_cpu.stime)) * 100 / total_delta_time,
            ((new_cpu.iowtime) - (old_cpu.iowtime)) * 100 / total_delta_time,
            ((new_cpu.irqtime + new_cpu.sirqtime)
                    - (old_cpu.irqtime + old_cpu.sirqtime)) * 100 / total_delta_time);
    printf("用户 %lu + 优先值为负 %lu + 系统 %lu + 空闲 %lu + IO %lu + 硬中断 %lu + 软中断 %lu = %lu\n",
            new_cpu.utime - old_cpu.utime,
            new_cpu.ntime - old_cpu.ntime,
            new_cpu.stime - old_cpu.stime,
            new_cpu.itime - old_cpu.itime,
            new_cpu.iowtime - old_cpu.iowtime,
            new_cpu.irqtime - old_cpu.irqtime,
            new_cpu.sirqtime - old_cpu.sirqtime,
            total_delta_time);
    printf("---------------------------------------\n");
    if (!threads) 
        printf("%5s %4s %1s %5s %7s %7s %-8s %s\n", "PID", "CPU%", "S", " #THR", "VSS", "RSS", "    UID", "    Name");
    else
        printf("%5s %5s %4s %1s %7s %7s %3s %-8s %-15s %s\n", "PID", "TID", "CPU%", "S", "VSS", "RSS", "PCY", "UID", "Thread", "Proc");
 
    for (i = 0; i < num_new_procs; i++) {
        proc = new_procs[i];
 
        if (!proc || (max_procs && (i >= max_procs)))
            break;
        user  = getpwuid(proc->uid);
        group = getgrgid(proc->gid);
        if (user && user->pw_name) {
            user_str = user->pw_name;
        } else {
            snprintf(user_buf, 20, "%d", proc->uid);
            user_str = user_buf;
        }
        if (group && group->gr_name) {
            group_str = group->gr_name;
        } else {
            snprintf(group_buf, 20, "%d", proc->gid);
            group_str = group_buf;
        }
        if (!threads) 
            printf("%5d %3lu%% %c %5d %6ldK %6luK %3s %-10.10s %s\n", proc->pid, proc->delta_time * 100 / total_delta_time, proc->state, proc->num_threads,
                proc->vss / 1024, proc->rss * getpagesize() / 1024, proc->policy, user_str, proc->name[0] != 0 ? proc->name : proc->tname);
        else
            printf("%5d %5d %3lu%% %c %6ldK %6luK %3s %-8.8s %-15s %s\n", proc->pid, proc->tid, proc->delta_time * 100 / total_delta_time, proc->state,
                proc->vss / 1024, proc->rss * getpagesize() / 1024, proc->policy, user_str, proc->tname, proc->name);
    }
}
 
static void free_old_procs(void) {
    int i;
 
    for (i = 0; i < num_old_procs; i++)
        if (old_procs[i])
            free_proc(old_procs[i]);
 
    free(old_procs);
}

void generateUserUsage() {
    printf("---------------------------------------\n");
    printf("当前用户\n");

    struct utmp *ut;

    setutent(); 
    ut = getutent(); 

    while (ut != NULL) {
        if (ut -> ut_type == USER_PROCESS) {
            printf("%s\n", ut -> ut_user); 
        }
        ut = getutent(); 
    }

}


void displaySystemInfo() {
    struct utsname uts;
    uname(&uts);
    printf("---------------------------------------\n");
}

bool isInteger(char *s) {
    int i = 0;
    while (s[i] != '\0') {
        if (isdigit(s[i]) == 0) {
            return false;
        }
        i++;
    }
    return true;
}

bool parseArguments(int argc, char **argv, int *samples, int *tdelay, bool *systemFlagPresent, 
                    bool *userFlagPresent, bool *graphicsFlagPresent) {
    
    bool samplesSpecified = false; 
    bool tdelaySpecified = false;
    
    if (argc > 1) {

        int i = 1;
        while (i < argc) {
            char *token = strtok(argv[i], "="); // split each argument at "="
            if (strcmp(token, "--samples") == 0) {
                *samples = atoi(strtok(NULL, "")); // store specified # of samples in samples
                samplesSpecified = true;
            }
            else if (strcmp(token, "--tdelay") == 0) {
                *tdelay = atoi(strtok(NULL, "")); // store specified delay in tdelay
                tdelaySpecified = true;
            }
            else if (strcmp(argv[i], "--system") == 0) { // if system flag indicated
                *systemFlagPresent = true;
            }
            else if (strcmp(argv[i], "--user") == 0) { // if user flag indicated
                *userFlagPresent = true;
            }
            else if ((strcmp(argv[i], "--graphics") == 0) ||  (strcmp(argv[i], "-g") == 0)) { // if graphics flag indicated
                *graphicsFlagPresent = true;
            }
            // treating as positional argument
            else if (isInteger(argv[i]) && i+1 < argc && isInteger(argv[i+1]) && !samplesSpecified && !tdelaySpecified) {
                *samples = atoi(argv[i]);
                *tdelay = atoi(argv[i+1]);
                samplesSpecified = true;
                tdelaySpecified = true;
                i++;
            }
            else if (isInteger(argv[i]) && !samplesSpecified) { // single numerical value entered
                *samples = atoi(argv[i]);
                samplesSpecified = true;
            }
            else if(!strcmp(argv[i], "-n")){
                printf("Invalid argument entered!\n");
                return false;
            }
            i++;
        }
    }


    return true;
}

void printReport(int samples, int tdelay, bool systemFlagPresent, 
                 bool userFlagPresent, bool graphicsFlagPresent) {
    
    UsageInfoLL *usageInfo = (UsageInfoLL *)calloc(1, sizeof(UsageInfoLL)); 

    usageInfo->last_mem_usage = -1; 

    usageInfo->lastTotal = -1;
    usageInfo->lastIdle = -1;

    int i = 0;
    while (i < samples) {
        printf("\x1b%d", 7); // save position

        if (systemFlagPresent && !graphicsFlagPresent) { // if system flag indicated without graphics
            generateMemoryUsage(samples, tdelay, usageInfo, i);
            generateCPUUsage(samples, tdelay, usageInfo, i);
        }
        if (systemFlagPresent && graphicsFlagPresent) { // if system and graphics flag indicated
            generateMemoryUsageGraphics(samples, tdelay, usageInfo, i);
            generateCPUUsageGraphics(samples, tdelay, usageInfo, i);
        }
        if (userFlagPresent) { // if user flag indicated
            generateUserUsage();
        }
        if (!systemFlagPresent && !userFlagPresent && !graphicsFlagPresent) { // if no flag indicated
            generateMemoryUsage(samples, tdelay, usageInfo, i);
            generateCPUUsage(samples, tdelay, usageInfo, i);
            generateUserUsage();
        }
        if (!systemFlagPresent && !userFlagPresent && graphicsFlagPresent) { // if no flag indicated except graphics
            generateMemoryUsageGraphics(samples, tdelay, usageInfo, i);
            generateCPUUsageGraphics(samples, tdelay, usageInfo, i);
            generateUserUsage();
        }

        if (i+1 < samples) { // if not printing last sample
            sleep(tdelay); // delay
            printf("\x1b%d", 8); // go back to saved position
        }
        i++;
    }
    deleteList(usageInfo->mem_usage_list_head); 
    deleteList(usageInfo->cpu_usage_list_head); 
    free(usageInfo); 

    displaySystemInfo(); 
}
 
static int proc_vss_cmp(const void *a, const void *b) {
    struct proc_info *pa, *pb;
 
    pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
 
    if (!pa && !pb) return 0;
    if (!pa) return 1;
    if (!pb) return -1;
 
    return -numcmp(pa->vss, pb->vss);
}
 
static int proc_rss_cmp(const void *a, const void *b) {
    struct proc_info *pa, *pb;
 
    pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
 
    if (!pa && !pb) return 0;
    if (!pa) return 1;
    if (!pb) return -1;
 
    return -numcmp(pa->rss, pb->rss);
}
 
static int proc_thr_cmp(const void *a, const void *b) {
    struct proc_info *pa, *pb;
 
    pa = *((struct proc_info **)a); pb = *((struct proc_info **)b);
 
    if (!pa && !pb) return 0;
    if (!pa) return 1;
    if (!pb) return -1;
 
    return -numcmp(pa->num_threads, pb->num_threads);
}
 

 
static void usage(char *cmd) {
    fprintf(stderr, "Usage: %s [ -m max_procs ] [ -n iterations ] [ -d delay ] [ -s sort_column ] [ -t ] [ -h ]\n"
                    "    -m num  Maximum number of processes to display.\n"
                    "    -n num  Updates to show before exiting.\n"
                    "    -d num  Seconds to wait between updates.\n"
                    "    -s col  Column to sort by (cpu,vss,rss,thr).\n"
                    "    -t      Show threads instead of processes.\n"
                    "    -h      Display this help screen.\n",
        cmd);
}

int main(int argc, char *argv[]) {
    int i;
 
    num_used_procs = num_free_procs = 0;
 
    max_procs = 0;
    delay = 3;
    iterations = -1;
    proc_cmp = &proc_cpu_cmp;
    
    for (i = 1; i < argc; i++) {
        if (!strcmp(argv[i], "-m")) {
            if (i + 1 >= argc) {
                fprintf(stderr, "Option -m expects an argument.\n");
                usage(argv[0]);
                exit(EXIT_FAILURE);
            }
            max_procs = atoi(argv[++i]);
            continue;
        }
        if (!strcmp(argv[i], "-n")) {
            if (i + 1 >= argc) {
                fprintf(stderr, "Option -n expects an argument.\n");
                usage(argv[0]);
                exit(EXIT_FAILURE);
            }
            iterations = atoi(argv[++i]);
            continue;
        }
        if (!strcmp(argv[i], "-d")) {
            if (i + 1 >= argc) {
                fprintf(stderr, "Option -d expects an argument.\n");
                usage(argv[0]);
                exit(EXIT_FAILURE);
            }
            delay = atoi(argv[++i]);
            continue;
        }
        if (!strcmp(argv[i], "-s")) {
            if (i + 1 >= argc) {
                fprintf(stderr, "Option -s expects an argument.\n");
                usage(argv[0]);
                exit(EXIT_FAILURE);
            }
            ++i;
            if (!strcmp(argv[i], "cpu")) { proc_cmp = &proc_cpu_cmp; continue; }
            if (!strcmp(argv[i], "vss")) { proc_cmp = &proc_vss_cmp; continue; }
            if (!strcmp(argv[i], "rss")) { proc_cmp = &proc_rss_cmp; continue; }
            if (!strcmp(argv[i], "thr")) { proc_cmp = &proc_thr_cmp; continue; }
            fprintf(stderr, "Invalid argument \"%s\" for option -s.\n", argv[i]);
            exit(EXIT_FAILURE);
        }
        if (!strcmp(argv[i], "-t")) { threads = 1; continue; }
        if (!strcmp(argv[i], "-h")) {
            usage(argv[0]);
            exit(EXIT_SUCCESS);
        }
        if (!strcmp(argv[i], "-g")) {
	    int samples = 10; 
	    int tdelay = 1; 
	    bool systemFlagPresent = false; 
	    bool userFlagPresent = false; 
	    bool graphicsFlagPresent = false; 
	    bool properArgs = parseArguments(argc, argv, &samples, &tdelay, &systemFlagPresent, &userFlagPresent, &graphicsFlagPresent);
	    if (!properArgs)
		return 1;   
	    printReport(samples, tdelay, systemFlagPresent, userFlagPresent, graphicsFlagPresent);
            exit(EXIT_SUCCESS);
        }
        fprintf(stderr, "Invalid argument \"%s\".\n", argv[i]);
        usage(argv[0]);
        exit(EXIT_FAILURE);
    }
 
    if (threads && proc_cmp == &proc_thr_cmp) {
        fprintf(stderr, "Sorting by threads per thread makes no sense!\n");
        exit(EXIT_FAILURE);
    }
 
    free_procs = NULL;
 
    num_new_procs = num_old_procs = 0;
    new_procs = old_procs = NULL;
 
    read_procs();
    while ((iterations == -1) || (iterations-- > 0)) {
        old_procs = new_procs;
        num_old_procs = num_new_procs;
        memcpy(&old_cpu, &new_cpu, sizeof(old_cpu));
        sleep(delay);
        read_procs();
        print_procs();
        free_old_procs();
    }
 
    return 0;
}
 

